package com.mkait.thief.handlerinterceptor;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mkait.thief.domain.User;
import com.mkait.thief.service.UserService;
import com.mkait.thief.util.PHPSessionUtils;
import com.mkait.thief.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class AuthHandlerInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理之前进行调用（Controller方法调用之前）
        String requestURI = request.getRequestURI();
        if (StringUtils.isEmpty(requestURI)){
            response.setStatus(403);
            return false;
        }
        // 获取cookie
        String cookie = request.getHeader("Cookie");
        if (StringUtils.isEmpty(cookie)){
            response.setStatus(403);
            return false;
        }
        // 获取token
        String token = request.getHeader("Cookie").split(";")[0];
        if (StringUtils.isEmpty(token)){
            response.setStatus(403);
            return false;
        }
        token = token.split("=")[1];
        if (StringUtils.isEmpty(token)){
            response.setStatus(403);
            return false;
        }
        // 获取session
        String session = redisTemplate.opsForValue().get("PHPREDIS_SESSION:" + token);
        if (StringUtils.isEmpty(session)){
            response.setStatus(403);
            return false;
        }
        // 获取用户类型
        String userId = PHPSessionUtils.getUserId(session);
        int userType = PHPSessionUtils.getUserType(session);
        request.setAttribute("sessionUser",userId);
        log.info("用户id：{}的用户调用URL：{} ",userId , requestURI);
        if (requestURI.matches("/complaint/\\S+") || requestURI.matches("/refundVerify/\\S+") || requestURI.matches("/goodpool/\\S+")){
            if (userType == 2){
                response.setStatus(403);
                return false;
            }
            User user = userService.getById(userId);
            if (user == null ||user.getIsFreeze() == 1||user.getStatus() == 0){
                response.setStatus(403);
                return false;
            }
            return true;
        }else if (requestURI.matches("/thief/\\S+") || requestURI.matches("/refund/\\S+")){
            if (userType != 0){
                response.setStatus(403);
                return false;
            }
            return true;
        }
        response.setStatus(400);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }

}
